<template>
    <div class="client">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="6">
                    <el-form-item label="作业目的" prop="stat_cod">
                        <el-select
                            v-model="formData.stat_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                            :disabled="disabledControl"
                            @change="stateChange"
                        >
                            <el-option
                                v-for="optValue in cntrGateOutStat"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="计划名称" prop="plan_name">
                        <el-input v-model.trim="formData.plan_name" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item
                        :label="formDisplayControls.planDateLabel"
                        prop="plan_date"
                    >
                        <el-date-picker
                            v-model="formData.plan_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="6" v-if="formDisplayControls.cntrCorpIsShow">
                    <el-form-item label="客户" prop="cntr_corp_cod">
                        <el-select
                            v-model="formData.cntr_corp_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cntrCorp"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="箱主" prop="cntr_owner">
                        <el-select
                            v-model="formData.cntr_owner"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cntrOwner"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="尺寸" prop="cntr_siz_cod">
                        <el-select
                            v-model="formData.cntr_siz_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cntrSiz"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="箱型" prop="cntr_typ_cod">
                        <el-select
                            v-model="formData.cntr_typ_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cntrTyp"
                                :key="optValue.value"
                                :label="optValue.value"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="箱况" prop="dam_id">
                        <el-select
                            v-model="formData.dam_id"
                            :clearable="true"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cntrDam"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="站点" prop="cfs_cod">
                        <el-select
                            v-model="formData.cfs_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                            :disabled="disabledControl"
                        >
                            <el-option
                                v-for="optValue in cyCfs"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="放箱单号" prop="bill_no">
                        <textupperinput
                            :disabled="disabledControl"
                            v-model.trim="formData.bill_no"
                        ></textupperinput>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="箱量" prop="cntr_num">
                        <el-input-number
                            v-model.trim="formData.cntr_num"
                            :min="formData.cntr_work_num"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="已作业箱量" prop="cntr_work_num">
                        <el-input
                            v-model.trim="formData.cntr_work_num"
                            disabled
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="5" v-if="formDisplayControls.freeDaysIsShow">
                    <el-form-item label="免费天数" prop="free_days">
                        <el-input-number
                            v-model.trim="formData.free_days"
                            :min="0"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="5" v-if="formDisplayControls.dayRateIsShow">
                    <el-form-item label="出租费率" prop="day_rate">
                        <el-input-number
                            v-model.trim="formData.day_rate"
                            :min="0"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="5" v-if="formDisplayControls.currencyIsShow">
                    <el-form-item label="出租费货币" prop="currency_cod">
                        <el-select
                            v-model="formData.currency_cod"
                            :clearable="true"
                            filterable
                            placeholder="Select"
                        >
                            <el-option
                                v-for="optValue in currency"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="发送邮件" prop="need_email">
                        <el-switch
                            v-model.trim="formData.need_email"
                            :active-value="'Y'"
                            :inactive-value="'N'"
                        ></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="formData.remark" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="bank">
        <el-table
            ref="tableRef"
            :data="tableData"
            row-key="id"
            table-layout="auto"
            @row-dblclick="onFeeClick"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_owner"
                label="成本中心"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_owner"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in cntrOwner"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_owner, cntrOwner) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_in_out"
                label="收付"
                width="120"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_in_out"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in SelectOptionFeeInOut"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{
                            transFormatter(
                                scope.row.fee_in_out,
                                SelectOptionFeeInOut,
                            )
                        }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_unit_cod"
                label="客户"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_unit_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in client"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_unit_cod, client) }}
                    </template>
                </template>
            </el-table-column>

            
            <!-- <el-table-column
                v-bind:align="'center'"
                prop="fee_typ_cod"
                label="费用类型"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_typ_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in feetyp"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_typ_cod, feetyp) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="fee_cod"
                label="费目"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.fee_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in feecod"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.fee_cod, feecod) }}
                    </template>
                </template>
            </el-table-column> -->
            <el-table-column
                v-bind:align="'center'"
                prop="currency_cod"
                label="货币"
                width="120"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-select
                            v-model="scope.row.currency_cod"
                            filterable
                            placeholder="Select"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in currency"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </template>
                    <template v-else>
                        {{ transFormatter(scope.row.currency_cod, currency) }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="amount"
                label="金额"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model="scope.row.amount"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.amount }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="remark"
                label="备注"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model="scope.row.remark"></el-input>
                    </template>
                    <template v-else>
                        {{ scope.row.remark }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-button
                            size="small"
                            type="primary"
                            @click="onOK(scope.$index, scope.row)"
                            >确定</el-button
                        >
                        <el-button
                            size="small"
                            type="info"
                            @click="onCancel(scope.$index, scope.row)"
                            >取消</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="onDel(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="btn-group">
        <el-button-group>
            <el-button
                class="btn"
                type="primary"
                v-debounce="submitForm"
                size="large"
            >
                保存
            </el-button>
            <el-button
                class="btn"
                type="primary"
                v-debounce="submitAndNewForm"
                size="large"
            >
                保存并新增
            </el-button>
            <!-- <el-button
                class="btn"
                type="primary"
                @click="addDefaultFee"
                size="large"
                >默认费用</el-button
            > -->
            <el-button class="btn" type="primary" @click="addFee" size="large"
                >增加费用</el-button
            >
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="OutPlan">
import { ref, reactive, onMounted, computed } from 'vue';
import { storeToRefs } from 'pinia';
import {
    ElMessage,
    ElMessageBox,
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';

import type { OutPlanModel, PlanFeedetModel } from '@/common/types/container';
import { Request } from '@/app/request';

import { initObjectProperty, transFormatter } from '@/common/tools';
import { isNil, omit, template } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
import { useAppStore } from '@/store/app';
import textupperinput from '@/components/forms/TextUpperInput.vue';

const {
    cntrDam,
    cntrSiz,
    cntrTyp,
    cntrCorp,
    
    cyCfs,
    cntrOwner,
    client,
    SelectOptionFeeInOut,
    feecod,
    
    currency,
    cntrGateOutStat,
} = storeToRefs(useAppStore());

const props = defineProps<{
    plan: OutPlanModel;
}>();
const temFeedet: PlanFeedetModel = {};
const formRef = ref<FormInstance>();
const formData = reactive<OutPlanModel>({});
const tableRef = ref<TableRefs>();
const tableData = reactive<PlanFeedetModel[]>([]);
const rules = reactive<FormRules>({
    plan_name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    plan_date: [{ required: true, message: '请输入计划日期', trigger: 'blur' }],
    stat_cod: [
        {
            required: true,
            message: '请选择作业目的',
            trigger: 'blur',
        },
    ],
    cntr_siz_cod: [
        {
            required: true,
            message: '请输入箱尺寸',
            trigger: 'blur',
        },
    ],
    cntr_typ_cod: [
        {
            required: true,
            message: '请输入箱型',
            trigger: 'blur',
        },
    ],
    cntr_num: [
        {
            required: true,
            message: '请输入箱量',
            trigger: 'blur',
        },
    ],
    /* cntr_corp_cod: [
        {
            required: true,
            message: '请输入客户',
            trigger: 'blur',
        },
    ], */
    cntr_owner: [
        {
            required: true,
            message: '请输入箱主',
            trigger: 'blur',
        },
    ],
    cfs_cod: [
        {
            required: true,
            message: '请输入站点',
            trigger: 'blur',
        },
    ],
    /* dam_id: [
        {
            required: true,
            message: '请输入箱况',
            trigger: 'blur',
        },
    ], */
    bill_no: [
        {
            required: true,
            message: '请输入放箱单号',
            trigger: 'blur',
        },
    ],
});
const cascaderprops = {
    // checkStrictly: false,
    expandTrigger: 'hover' as const,
};
const emit = defineEmits<{
    create: [action: OutPlanModel];
    update: [action: OutPlanModel];
    close: [];
}>();
const disabledControl = computed(() => {
    if (props.plan.id) {
        // 修改
        if (formData.cntr_work_num && formData.cntr_work_num > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
});
const formDisplayControls = reactive<{
    planDateLabel: string,
    cntrCorpIsShow: boolean,
    freeDaysIsShow: boolean,
    dayRateIsShow: boolean,
    currencyIsShow: boolean,
}>({
    planDateLabel: '放箱日期',
    cntrCorpIsShow: false,
    freeDaysIsShow: false,
    dayRateIsShow: false,
    currencyIsShow: false,
});
const stateChange = (state: string) => {
    if (state === 'EODXCC') {
        formDisplayControls.cntrCorpIsShow = true;
        formDisplayControls.planDateLabel = '放箱日期';
        formDisplayControls.freeDaysIsShow = false;
        formDisplayControls.dayRateIsShow = false;
        formDisplayControls.currencyIsShow = false;
    }
    if (state === 'EOQZCC') {
        formDisplayControls.cntrCorpIsShow = true;
        formDisplayControls.planDateLabel = '合同日期'
        formDisplayControls.freeDaysIsShow = true;
        formDisplayControls.dayRateIsShow = true;
        formDisplayControls.currencyIsShow = true;
    }
    if (state === 'EOZYXC') {
        formDisplayControls.cntrCorpIsShow = false;
        formDisplayControls.planDateLabel = '放箱日期'
        formDisplayControls.freeDaysIsShow = false;
        formDisplayControls.dayRateIsShow = false;
        formDisplayControls.currencyIsShow = false;
    }
};
onMounted(() => {
    Object.assign(formData, omit(props.plan, ['fees']));
    if (props.plan.stat_cod) {
        stateChange(props.plan.stat_cod);
    }
    if (props.plan.fees) {
        props.plan.fees!.forEach((element) => {
            tableData.push(element);
        });
    }
});
const save = async () => {


    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );
    if (formValid) {
        for (let index = 0; index < tableData.length; index++) {
            tableData[index].cascaderfeecod = undefined;
            const element = tableData[index];

            if (element.isEdit) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '存在未确定数据',
                });
                return;
            }
        }
        if (formData.id! > 0) {
            // 修改
            const updateFeeFlag = await ElMessageBox.confirm(
                '是否修改已出场箱费用?',
                '提示',
                {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'info',
                },
            )
                .then(() => {
                    return true;
                })
                .catch(() => {
                    return false;
                });

            formData['updateFeeFlag'] = updateFeeFlag;
            formData['fees'] = tableData;
            const req = new Request('出场计划修改', formData);
            const r = await req.post();
            if (r.code > 100) {
                emit('update', r.obj);
                if (r.ext?.status === '失败') {
                    ElMessage({
                        type: 'info',
                        dangerouslyUseHTMLString: true,
                        message: r.ext.msg,
                    });
                }
                return true;
            }
        } else {
            // 新增
            const param = omit(formData, ['id']);
            param['fees'] = tableData;
            // param.carry_id = 'A';
            const req = new Request('出场计划增加', param);
            const r = await req.post();
            if (r.code > 100) {
                emit('create', r.obj);
                if (r.ext?.status === '失败') {
                    ElMessage({
                        type: 'info',
                        dangerouslyUseHTMLString: true,
                        message: r.ext.msg,
                    });
                }
                return true;
            }
        }
    } else {
        return false;
    }
};
const submitForm = async () => {
    const r = await save();
    if (r) {
        emit('close');
    }
};

const submitAndNewForm = async () => {
    const r = await save();
    if (r) {
        reset();
    }
};
const reset = () => {
    initObjectProperty(formData);
    initObjectProperty(temFeedet);
    tableData.length = 0;
};
const addFee = () => {

    tableData.push({
        isEdit: true,
    });
    initObjectProperty(temFeedet);
};

const onOK = (_index: number, row: PlanFeedetModel) => {
    if (row.cascaderfeecod) {
        row.fee_typ_cod = row.cascaderfeecod[0];
        row.fee_cod = row.cascaderfeecod[1];
    } else {
        row.fee_typ_cod = undefined;
        row.fee_cod = undefined;
    }
    row.isEdit = false;
    row.cascaderfeecod = undefined;
    initObjectProperty(temFeedet);
};
const onCancel = (_index: number, row: PlanFeedetModel) => {
    Object.assign(row, temFeedet);
    row.cascaderfeecod = undefined;
    row.isEdit = false;
};
const onDel = (index: number, row: PlanFeedetModel) => {
    tableData.splice(index, 1);
};
const onFeeClick = (row: any, column: any, event: Event) => {
    row.cascaderfeecod = [];
    if (row.fee_typ_cod) {
        row.cascaderfeecod[0] = row.fee_typ_cod;
    }
    if (row.fee_cod) {
        row.cascaderfeecod[1] = row.fee_cod;
    }
    Object.assign(temFeedet, omit(row, ['isEdit']));
    row.isEdit = true;
};
// formRef.value?.clearValidate(['cntr_owner', 'cntr_corp_cod']);
</script>
<style lang="scss" scoped>
.client {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.bank {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
